package com.bjb.vr.gateway.exception;

import com.bjb.vr.common.result.BaseErrorCode;
import com.bjb.vr.common.utils.DateTimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.ResourceProperties;
import org.springframework.boot.autoconfigure.web.reactive.error.DefaultErrorWebExceptionHandler;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpStatus;
import org.springframework.web.reactive.function.server.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 网关自定义全局异常处理
 *
 * @description:
 * @author: HuJingBo
 * @time: 2022/3/14 10:59
 */
@Slf4j
public class GatewayExceptionHandler extends DefaultErrorWebExceptionHandler {

    public GatewayExceptionHandler(ErrorAttributes errorAttributes, ResourceProperties resourceProperties, ErrorProperties error, ApplicationContext applicationContext) {
        super(errorAttributes, resourceProperties, error, applicationContext);
    }


    /**
     * 获取异常属性
     */
    @Override
    protected Map<String, Object> getErrorAttributes(ServerRequest request, ErrorAttributeOptions options) {
        Integer code = Integer.valueOf(BaseErrorCode.UNKNOWN_ERROR.getCode());
        Throwable error = super.getError(request);
        if (error instanceof NullPointerException) {
            code = Integer.valueOf(BaseErrorCode.NOTFOUND.getCode());
        }
        return response(code, this.buildMessage(request, error));
    }

    /**
     * 指定响应处理方法为JSON处理的方法
     *
     * @param errorAttributes
     */
    @Override
    protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {
        return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);
    }

    /**
     * 根据code获取对应的HttpStatus
     *
     * @param errorAttributes
     */
    @Override
    protected int getHttpStatus(Map<String, Object> errorAttributes) {
        int statusCode = (int) errorAttributes.get("code");
        return HttpStatus.valueOf(statusCode).value();
    }

    /**
     * 构建异常信息
     *
     * @param request
     * @param ex
     * @return
     */
    private String buildMessage(ServerRequest request, Throwable ex) {
        StringBuilder message = new StringBuilder("请检查请求目标路径或服务是否正确 ");
        message.append("[");
        message.append(request.methodName());
        message.append(" ");
        boolean containsKey = request.attributes().containsKey("org.springframework.cloud.gateway.support.ServerWebExchangeUtils.gatewayRequestUrl");
        if (containsKey) {
            message.append(request.attribute("org.springframework.cloud.gateway.support.ServerWebExchangeUtils.gatewayRequestUrl"));
        } else {
            message.append(request.uri());
        }
        message.append("]");
        return message.toString();
    }

    /**
     * 构建返回的JSON数据格式
     *
     * @param status       状态码
     * @param errorMessage 异常信息
     * @return
     */
    public static Map<String, Object> response(int status, String errorMessage) {
        Map<String, Object> map = new HashMap<>();
        map.put("success", false);
        map.put("code", status);
        map.put("message", errorMessage);
        map.put("timestamp", DateTimeUtil.nowStrTime());
        log.error(map.toString());
        return map;
    }
}
